package com.pz.minioproxy.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Configuration
@Slf4j
@RefreshScope
public class MinioConfig {
    @Value("${minio.serverAddr}")
    private String serverAddr;
    @Value("${minio.port}")
    private int port;
    @Getter
    @Value("${minio.bucket}")
    private String bucket1;
    private String bucket2 = "big-file";
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.accessSecret}")
    private String accessSecret;

    @Bean("minioClient")
    public MinioClient initMinioClient() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        MinioClient minioClient = MinioClient.builder()
                        .endpoint("http://"+serverAddr+":"+port)
                        .credentials(accessKey, accessSecret)
                        .build();
        boolean found1 =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket1).build());
        if (!found1) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket1).build());
        } else {
            log.info("Bucket ${} already exists.", bucket1);
        }

        boolean found2 =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket2).build());
        if (!found2) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket2).build());
        } else {
            log.info("Bucket ${} already exists.", bucket2);
        }
        return minioClient;
    }
}
